package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.OrderSettingDao;
import com.atguigu.pojo.OrderSetting;
import com.atguigu.service.OrderSettingService;
import com.atguigu.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    public void addBatch(List<OrderSetting> dataList) {
        if (dataList != null && dataList.size() > 0){
            for (OrderSetting orderSetting : dataList) {
                OrderSetting orderSettingdb = orderSettingDao.findByOrderData(orderSetting.getOrderDate());
                if (orderSettingdb == null){
                    orderSettingDao.add(orderSetting);
                }else {
                    if (orderSettingdb.getNumber() != orderSetting.getNumber()){
                        orderSettingDao.update(orderSetting);
                    }
                }



            }
        }
    }

    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String date) { // "2021-11"
        String start = date+"-01";
        //String end = date+"-31"; //并不是每个月都有31号。mysql8执行时会报错。
        String end = DateUtils.getLastDayOfMonth(date);

        Map dataParam = new HashMap();
        dataParam.put("start",start);
        dataParam.put("end",end);

        System.out.println("dataParam = " + dataParam);

        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(dataParam);

        List<Map<String, Integer>> resultList = new ArrayList<Map<String, Integer>>();
        for (OrderSetting orderSetting : list) {
            Map<String, Integer> mapObj = new HashMap<>();
            mapObj.put("date",orderSetting.getOrderDate().getDate());
            mapObj.put("number",orderSetting.getNumber());
            mapObj.put("reservations",orderSetting.getReservations());
            resultList.add(mapObj);
        }

        return resultList;
    }

    @Override
    public void saveOrUpdate(OrderSetting orderSetting) {
        OrderSetting orderSettingdb = orderSettingDao.findByOrderData(orderSetting.getOrderDate());
        if(orderSettingdb ==null){
            orderSettingDao.add(orderSetting);
        }else {
            orderSettingDao.update(orderSetting);
        }
    }
}
